package com.macro.mall.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.macro.mall.common.config.XhsApiConfig;
import com.macro.mall.common.exception.XhsApiException;
import com.macro.mall.model.request.Code2SessionRequest;
import com.macro.mall.model.response.Code2SessionResponse;
import com.macro.mall.service.SessionService;
import com.macro.mall.service.XhsLoginService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

@Service
@Slf4j
public class SessionServiceImpl implements SessionService {

    @Resource
    private OkHttpClient httpClient;

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private XhsApiConfig apiConfig;

    @Resource
    private XhsLoginService xhsLoginService;

    @Override
    public Code2SessionResponse code2Session(Code2SessionRequest request) {
        // 1. 参数校验
        if (request == null || request.getCode() == null || request.getCode().isEmpty()) {
            throw new IllegalArgumentException("code不能为空");
        }

        // 2. 获取API地址
        String apiUrl = apiConfig.getBaseUrl() + "/api/rmp/session";

        // 3. 获取有效token
        String validToken;
        try {
            validToken = xhsLoginService.getValidToken();
        } catch (XhsApiException e) {
            log.error("获取access_token失败", e);
            throw new RuntimeException("获取access_token失败", e);
        }

        try {
            // 4. 构建请求URL
            HttpUrl url = HttpUrl.parse(apiUrl).newBuilder()
                    .addQueryParameter("app_id", apiConfig.getAppId())
                    .addQueryParameter("access_token", validToken)
                    .addQueryParameter("code", request.getCode())
                    .build();

            // 5. 构建HTTP请求
            Request httpRequest = new Request.Builder()
                    .url(url)
                    .get()
                    .build();

            // 6. 执行请求并处理响应
            try (Response response = httpClient.newCall(httpRequest).execute()) {
                if (!response.isSuccessful()) {
                    log.error("code2Session失败，HTTP状态码: {}", response.code());
                    throw new RuntimeException("API请求失败，状态码: " + response.code());
                }

                // 7. 解析响应数据
                String responseBody = response.body().string();
                return objectMapper.readValue(responseBody, Code2SessionResponse.class);
            }
        } catch (IOException e) {
            log.error("code2Session异常", e);
            throw new RuntimeException("code2Session异常", e);
        }
    }
}
